package user

import (
	"context"
	"database/sql"
	"errors"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"ns/app/applet/api/internal/code"
	"ns/pkg/valids"
	"ns/pkg/xcode"
	"ns/pkg/xctx"
	"ns/pkg/xtypes"

	"ns/app/applet/api/internal/svc"
	"ns/app/applet/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserLogic {
	return &UpdateUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateUserLogic) UpdateUser(req *types.UpdateUserRequest) (resp *types.UpdateUserResponse, err error) {
	uid := xctx.GetUidFromCtx(l.ctx)
	if uid == 0 {
		return nil, xcode.NoLogin
	}

	// 校验手机号
	if valids.ValidMobile(req.Mobile) == false {
		return nil, code.ErrMobileInvalid
	}

	// 验证手机号是否已经存在
	user, err := l.svcCtx.UserModel.FindOneByMobile(l.ctx, req.Mobile)
	if err != nil {
		if !errors.Is(err, sqlx.ErrNotFound) {
			return nil, err
		}
	}
	// 如果手机号存在，且ID不相同，则返回错误
	if err == nil && req.Id != user.Id {
		return nil, code.ErrMobileExist
	}

	//  判断用户类型
	if !valids.ValidUserType(req.Type) {
		return nil, code.ErrUserTypeInvalid
	}
	// 判断用户等级
	if !valids.ValidAreaLevel(xtypes.AreaLevel{
		AreaCode: xtypes.AreaCode{
			Province: req.Province,
			City:     req.City,
			Area:     req.Area,
		},
	}) {
		return nil, code.ErrAreaLevelInvalid
	}

	// 更新用户信息
	user.Name = req.Name
	user.Mobile = req.Mobile
	user.Email = req.Email
	user.Type = req.Type
	user.Level = int64(req.Level)
	user.Province = req.Province
	user.City = sql.NullString{
		String: req.City,
		Valid:  true,
	}
	user.Area = sql.NullString{
		String: req.Area,
		Valid:  true,
	}
	user.CreatedBy = sql.NullInt64{
		Int64: uid,
		Valid: true,
	}
	err = l.svcCtx.UserModel.Update(l.ctx, user)
	if err != nil {
		return nil, err
	}
	return
}
